package example.controller;

import example.utils.DistributedLockHandler;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/redis")
public class RedisLockController {

    @Autowired
    private Redisson redisson;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private DistributedLockHandler distributedLockHandler;

    public static void main(String[] args) throws InterruptedException {
        long l = System.currentTimeMillis();
        Thread.sleep(2000);
        long l1 = 6000;
        long l2 = System.currentTimeMillis();
        System.out.println(l2 - l);
    }

    /**
     * redisson.getLock()  实现
     *
     * @return
     */
    @RequestMapping("/practice2")
    public String practice2() {
        String lockKey = "lockKey";
        String store = "qing";
        RLock redissonLock = redisson.getLock(lockKey);
        try {
//            redissonLock.lock(30, TimeUnit.SECONDS);
            boolean b = redissonLock.tryLock(3, 30, TimeUnit.SECONDS);
            if (!b) {
                return "服务器繁忙，请稍后重试";
            }
            int qing = Integer.parseInt(redisTemplate.opsForValue().get(store));
            Thread.sleep(10000);
            if (qing > 0) {
                int realQing = qing - 1;
                redisTemplate.opsForValue().set(store, realQing + "");
                System.out.println("扣减成功，库存剩余：" + redisTemplate.opsForValue().get(store));
            } else {
                System.out.println("Error, 库存不足");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            redissonLock.unlock();
        }
        return "Success";
    }

    /**
     * redis.opsForValue() 实现
     *
     * @return
     */
    @RequestMapping("/practice")
    public String practice() {
        String uuid = UUID.randomUUID().toString();
        String lockKey = "lockKey";
        String store = "qing";
        try {
//            int i = 0;
//            while(true){
//                if (redisTemplate.opsForValue().setIfAbsent(lockKey, uuid, 5, TimeUnit.SECONDS)) {
//                    break;
//                }
//                Thread.sleep(2000);
//                i++;
//                if(i == 3){
//                    System.out.println("抢占锁， " + Thread.currentThread().getName());
//                    return "系统繁忙，稍后重试";
//                }
//            }

            boolean lock = distributedLockHandler.lock(lockKey, uuid, 6, TimeUnit.SECONDS, 3000);
            if (!lock) {
                return "服务器繁忙，请稍后重试。。。";
            }

            int qing = Integer.parseInt(redisTemplate.opsForValue().get(store));
            if (qing > 0) {
                int realQing = qing - 1;
                redisTemplate.opsForValue().set(store, realQing + "");
                System.out.println("扣减成功，库存剩余：" + redisTemplate.opsForValue().get(store));
            } else {
                System.out.println("Error, 库存不足");
            }
        } finally {
            distributedLockHandler.releaseLock(lockKey, uuid);
//            if (uuid.equals(redisTemplate.opsForValue().get(lockKey))) {
            // 释放锁
//                redisTemplate.delete(lockKey);
//            }
        }
        return "Success";
    }
}
